// pages/addCart/addCart.js
var app = getApp();
var aCity = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" }
Page({

    /**
     * 页面的初始数据
     */
    data: {
        vehicleType: ["小箱货", "大货车"], //车辆类型
        vehicleTypeIndex: 0, //车辆索引
        oilType: ["0#柴油", "5#柴油", "-10#柴油", "-20#柴油", "-35#柴油", "-50#柴油", "90号（京89）汽油", "93号（京92）汽油", "97号（京95）汽油", "98号汽油"], //油品类型
        oilTypeIndex: 0, //油品类型索引
        legalECT: ["父亲", "母亲", "妻子", "伴侣", "自己"], //车辆法人紧急联系人类型
        legalECTIndex: 0, //车辆法人紧急联系人类型索引
        cartTypeIndex: 0, //车型索引
        brandList: [], //车辆品牌
        brandIndex: 0, //车辆品牌索引
        driveLicenseFront: "", //行驶证正面照片地址
        transportLicenseFront: "", //运输资格证正面照片地址
        vehicleFront: "", //车头照片地址
        vehicleBack: "" //车尾照片地址
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var test = 1
        var that = this
        that.setData({
                id: options.id
            })
            // console.log(typeof parseFloat(test.toFixed(2)), parseFloat(test.toFixed(2)))
        app.getApi.request("/api/Vehicles/Detail?id=" + options.id, {}, "GET", (res) => {
            that.setData({
                cartDetail: res.data.obj,
                legalECTIndex: res.data.obj.legalEmergencyContactType - 1,
                oilTypeIndex: res.data.obj.oilType - 1,
                vehicleTypeIndex: res.data.obj.vehicleType - 1,
                driveLicenseFront: res.data.obj.driveLicenseFront,
                transportLicenseFront: res.data.obj.transportLicenseFront,
                vehicleFront: res.data.obj.vehicleFront,
                vehicleBack: res.data.obj.vehicleBack,

            })
        }, (res) => {})
        app.getApi.request("/api/VehicleModel/All", { driverId: app.getApi.drivers.id, avatarUrl: that.data.avatar }, "GET", (res) => {
            that.setData({
                cartType: res.data.obj
            })
        }, (res) => {})
        app.getApi.request("/api/VehicleBrandModel/AllBrands", {}, "GET", (res) => {
            that.setData({
                brandList: res.data.obj
            })
        }, (res) => {})
    },
    vehicleType(e) { //车辆类型
        this.setData({
            vehicleTypeIndex: e.detail.value
        })
    },
    cartType(e) { //车型类型
        this.setData({
            cartTypeIndex: e.detail.value
        })
    },
    legalECTIndex(e) { //紧急联系人类型
        this.setData({
            legalECTIndex: e.detail.value
        })
    },
    brandList(e) { //车辆品牌
        this.setData({
            brandIndex: e.detail.value
        })
    },
    oilType(e) { //油品类型
        this.setData({
            oilTypeIndex: e.detail.value
        })
    },
    UpdateAvatar() { //更新头像
        var that = this
        that.upLoadImage(5)
        app.getApi.request("/api/Drivers/UpdateAvatar", { driverId: app.getApi.drivers.id, avatarUrl: that.data.avatar }, "POST", (res) => {
            console.log(res)
        }, (res) => {})

    },
    isCardID(sId) {
        var iSum = 0;
        var info = "";
        if (!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
        sId = sId.replace(/x$/i, "a");
        if (aCity[parseInt(sId.substr(0, 2))] == null) return "你的身份证地区非法";
        var sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
        var d = new Date(sBirthday.replace(/-/g, "/"));
        if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) return "身份证上的出生日期非法";
        for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
        if (iSum % 11 != 1) return "你输入的身份证号非法";
        //aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女");//此次还可以判断出输入的身份证号的人性别
        return true;
    },
    identityZ() {
        this.upLoadImage(1)
            // console.log(datas)
    },
    identityF() {
        this.upLoadImage(2)
            // console.log(datas)
    },
    driversZ() {
        this.upLoadImage(3)
            // console.log(datas)
    },
    driversF() {
        this.upLoadImage(4)
            // console.log(datas)
    },
    formSubmit(e) {
        // console.log(e)
        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        var vlu = e.detail.value;
        // console.log(this.isCardID(vlu.legalIdentityNumber), "ssssssssssss")
        // console.log(app.getApi)
        if (!myreg.test(vlu.vehicleLegalPersonTel) || !myreg.test(vlu.legalEmergencyContactTel)) {
            this.showMoadl("手机号码不正确")
            return;
        }
        if (vlu.name == "") {
            this.showMoadl("名字不能为空")
            return;
        }
        if (vlu.plateNumber == "") {
            this.showMoadl("车牌号不能为空")
            return;
        }
        if (vlu.weight == "") {
            this.showMoadl("装载重量不能为空")
            return;
        }
        if (vlu.legalIdentityNumber == "") {
            this.showMoadl("身份证号码不能为空")
            return;
        }
        if (vlu.carLength == "") {
            this.showMoadl("车长不能为空")
            return;
        }
        if (vlu.carWidth == "") {
            this.showMoadl("车宽不能为空")
            return;
        }
        if (vlu.carHeight == "") {
            this.showMoadl("车高不能为空")
            return;
        }
        if (!this.isCardID(vlu.legalIdentityNumber)) {
            this.showMoadl(this.isCardID(vlu.legalIdentityNumber))
        }
        if (vlu.drivingNumber == "") {
            this.showMoadl("行驶证号不能为空")
            return;
        }
        if (vlu.brandName == "") {
            this.showMoadl("运输资格证不能为空")
            return;
        }
        if (vlu.vehicleLegalPersonName == "") {
            this.showMoadl("车辆法人姓名不能为空")
            return;
        }
        if (vlu.legalIdentityNumber == "") {
            this.showMoadl("车辆法人身份证号不能为空")
            return;
        }
        if (vlu.vehicleLegalPersonTel == "") {
            this.showMoadl("法人联系电话不能为空")
            return;
        }
        if (vlu.legalEmergencyContactTel == "") {
            this.showMoadl("紧急联系人电话不能为空")
            return;
        }
        var datas = vlu;
        datas.id = this.data.id
        datas.carLength = parseFloat(Number(vlu.carLength).toFixed(2))
        datas.carWidth = parseFloat(Number(vlu.carWidth).toFixed(2))
        datas.carHeight = parseFloat(Number(vlu.carHeight).toFixed(2))
        datas.weight = parseFloat(Number(vlu.weight).toFixed(2))
        datas.driveLicenseIssuingDate = this.data.dLID
            // datas.vehicleType = Number(this.data.vehicleTypeIndex) + 1
        datas.vehicleType = 1
        datas.oilType = Number(this.data.oilTypeIndex) + 1
        datas.legalEmergencyContactType = Number(this.data.legalECTIndex) + 1
        datas.driveLicenseFront = this.data.driveLicenseFront
        datas.transportLicenseFront = this.data.transportLicenseFront
        datas.vehicleFront = this.data.vehicleFront
        datas.vehicleBack = this.data.vehicleBack
            // datas.id = app.getApi.drivers.id
        datas.vehicleBrandModels = {
            id: this.data.brandList[this.data.brandIndex].id,
            brandName: this.data.brandList[this.data.brandIndex].brandName,
            vehicleModel: this.data.brandList[this.data.brandIndex].vehicleModel,
            brandAndVehicleModel: this.data.brandList[this.data.brandIndex].brandAndVehicleModel
        }
        datas.vehicleModel = {
            id: this.data.cartType[this.data.cartTypeIndex].id,
            name: this.data.cartType[this.data.cartTypeIndex].name,
            lowestDriverLicenseType: this.data.cartType[this.data.cartTypeIndex].lowestDriverLicenseType,
            lowestDriverLicenseTypeName: this.data.cartType[this.data.cartTypeIndex].lowestDriverLicenseTypeName
        }
        datas.drivers = {
            id: app.getApi.drivers.id,
            name: app.getApi.drivers.name,
            tel: app.getApi.drivers.tel
        }
        datas.company = {
            id: app.getApi.company.id,
            name: app.getApi.company.companyName
        }

        if (app.getApi.company == null) {
            datas.company = {
                id: "",
                companyName: ""
            }
        } else {
            datas.company = {
                id: app.getApi.company.id,
                companyName: app.getApi.company.companyName
            }
        }
        app.getApi.request("/api/Vehicles/Edit", datas, "POST", (res) => {
            if (res.data.responseCode == 1000) {
                wx.showToast({
                    title: "修改成功",
                    icon: 'success',
                    duration: 2000,
                });
                setTimeout(function() {
                    wx.navigateBack({
                        delta: 1
                    })
                }, 2000)
            } else {
                wx.showToast({
                    title: '修改失败',
                    icon: 'loading',
                    duration: 2000
                });
            }


        }, (res) => {})


    },
    showMoadl(title) {
        wx.showModal({
            title: '提示',
            content: title,
            success: function(res) {
                if (res.confirm) {

                }
            }
        })
    },
    upLoadImage(isType) {
        var that = this
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths

                wx.uploadFile({
                    url: 'https://driverapi.dwilms.com/api/Upload/UploadOnePic', //仅为示例，非真实的接口地址
                    filePath: tempFilePaths[0],
                    name: 'file',
                    formData: {},
                    success: function(res) {
                        var data = JSON.parse(res.data)
                        console.log(data)
                        switch (isType) {
                            case 1:
                                that.setData({
                                    driveLicenseFront: data.obj
                                })
                                break;
                            case 2:
                                that.setData({
                                    transportLicenseFront: data.obj

                                })
                                break;
                            case 3:
                                that.setData({
                                    vehicleFront: data.obj

                                })
                                break;
                            case 4:
                                that.setData({
                                    vehicleBack: data.obj

                                })
                                break;
                            case 5:
                                that.setData({
                                    avatar: data.obj

                                })
                                break;
                        }


                    }
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})